# Maintainer: Biswapriyo Nath <nathbappai@gmail.com>

_realname=flann
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.9.2
pkgrel=1
pkgdesc="Fast Library for Approximate Nearest Neighbors (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/flann-lib/flann'
license=('spdx:BSD-3-Clause')
depends=(
  "${MINGW_PACKAGE_PREFIX}-gcc-libs"
  "${MINGW_PACKAGE_PREFIX}-hdf5"
  "${MINGW_PACKAGE_PREFIX}-lz4"
  "${MINGW_PACKAGE_PREFIX}-omp"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-pkgconf"
  "${MINGW_PACKAGE_PREFIX}-python"
)
source=("https://github.com/flann-lib/flann/archive/${pkgver}/${_realname}-${pkgver}.tar.gz"
        0001-flann-remove-fullpath-pkgconfig.patch
        0002-flann-cmake-fix-omp-library.patch)
sha256sums=('e26829bb0017f317d9cc45ab83ddcb8b16d75ada1ae07157006c1e7d601c8824'
            '23db2da074d4126ceb7ae9cdd95d438f933f1795b6b84c40419ee5409f5f7a54'
            '84f10a7f28a140ba71f5d340b9353f15c7881cff1af5574a4f576c95253aa4c1')

prepare() {
  cd "${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}"/0001-flann-remove-fullpath-pkgconfig.patch
  patch -p1 -i "${srcdir}"/0002-flann-cmake-fix-omp-library.patch

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    sed -i "s/-lgomp/-lomp/g" src/matlab/CMakeLists.txt
  fi
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DBUILD_EXAMPLES=OFF \
      -DBUILD_MATLAB_BINDINGS=OFF \
      -DBUILD_PYTHON_BINDINGS=ON \
      -DBUILD_TESTS=OFF \
      -DPYTHON_EXECUTABLE="${MINGW_PREFIX}/bin/python.exe" \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/COPYING" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/COPYING"

  # remove path reference in cmake
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/${_realname}/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
    sed -e "s|${MINGW_PREFIX}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
